# -*- coding: utf8 -*-
"""
Function attributes:
* load: boolean. If False the function will not load. Optional.
* name: strinbot.logs. Optional.
* thread: boolean. If True, Function will work by starting a thread. Optional.
* rule: string or regexp object. Requered.
* aliases: list of strings or regexp objects. Optional.
"""
#
# functions to parse incoming messages from rc (recent changes bot user).
#
import re, time
from util.functions import *
from util.wm_funcs import *
from util.pywikilib import Site, Page, User, NoSuchPage, WikiLink
import wikisite

"""
bot.ctrl_msg		=	bot.main_msg(evt, "##bots-ca", msg)
bot.vnd_msg			=	bot.main_msg(evt, "#wikipedia-ca-vandalisme", msg)
bot.patrol_msg      =	bot.main_msg(evt, "#wikipedia-ca-patrol", msg)
bot.newpages_msg	=	bot.main_msg(evt, "#wikipedia-ca", msg)
"""
load = False
langs = wikisite.ranking("ca", WikiLink("", "ca", "wikipedia"))
langs = re.search(r"\d+\. (\w+) [\d.]+ \(\+[\d.]+\) \|[^|]+\| \d+\. (\w+) [\d.]+ \(\-[\d.]+\)", langs)
wm_langs = list(langs.groups())+["ca"] if langs else ["uk","war","ca"]
wm_chans = ",".join(["#%s.wikipedia" % lang for lang in wm_langs])
speaker = {
	"fi": u"finés",
	"no": u"noruec",
	"zh": u"xinés",
	"pl": u"polonés",
	"uk": u"ucraïnés",
	"war": "waray-waray",
	"_def": "usuari d'una wiki desconeguda (%s)"
}
_prev = {"code": wm_langs[0], "gent": speaker[wm_langs[0]]}
_main = {"code": "ca", "gent": ""}
_next = {"code": wm_langs[1], "gent": speaker[wm_langs[1]]}

print "[%s] loading data from:" % time.strftime("%H:%M:%S")
for proj in (_prev, _main, _next):
	proj['chan'] = "#%s.wikipedia" % proj['code']
	s = Site(proj['code'])
	print "\t%s" % s.sitename()
	proj['site'] = s.load_siteinfo()

projects = (_prev, _main, _next)
loan_projects = (projects[0], projects[2])
def join_channels(bot, evt, cmd):
	#print "[%s] JOIN_CHANS %s %s  %s" % ( time.strftime("%H:%M:%S"), evt.chan, evt.source, bot.nickname )
	if evt.source == bot.nickname and evt.msg == bot.defchan:
		bot.join(",".join([proj['chan'] for proj in loan_projects]))
		bot.ctrl_msg(evt, "wmBot joined: %s" % ",".join([proj['chan'] for proj in loan_projects]))
join_channels.rule = "join"
join_channels.evttypes = ("join",)

def get_site(string):
	"""Usually sended from irc wikimedia bot, it tries to return the Site object
	of the project related to rc channel.
	"""
	lang, fam= string.lstrip("#").split(".")
	for proj in projects:
		if proj['code'] == lang:
			return proj['site']
	return Site(lang, fam).load_siteinfo()

def check_changes(page, oldid, diff):
	wrong=[]
	missing=[]

	newv, oldv = page.revisions(oldid, diff)

	"""
	added = removed = ''
	for word in difflib.ndiff(oldv.split(), newv.split()):
		if word.startswith('+'):
			added += word[2:] + ' '
		elif word.startswith('-'):
			removed += word[2:] + ' '
		added = added.strip()
		removed = removed.strip()
	print "noves",added.encode("ascii","replace")
	print "tretes",removed.encode("ascii","replace")
	print
	"""

	#cerquem si s'ha escrit un text únicament amb majúscules
	if not re.search(ur'(?:[A-ZÑÇÁÀÉÈÍÏÓÒÚÙÜ]+ ){3,}', oldv, re.U) and \
	(u"<!-- comença la taula" not in newv.lower() or "==bibliografia==" not in newv.lower()):
		m  = re.search(ur'([A-ZÑÇÁÀÉÈÍÏÓÒÚÙÜ]+ ){3,}', newv, re.U)
		if m:
			wrong.append(m.group(1))

	#convertim el text a minúscules per cercar coincidències
	oldv=oldv.lower()
	newv=newv.lower()

	#cerquem elements inapropiats
	for regexp in blacklist:
		if not re.search(regexp, oldv): #, re.U):
			m = re.search(ur"(%s)" % regexp, newv) #, re.U)
			if m:
				word = re.sub(ur"\n"," ",m.group(1))
				wrong.append(word)

	#treiem enllaços i codi htlm de colors, interpretats com elements inapropiats
	#per la regexp ur"[bcçdefghjklmnñpqrstvwxz]{5,}"
	regexps = [ur"https://.*?([bcdefghjklmnpqrstvwxz]{5,})", ur"#([abcdef]{6})"]
	for regexp in regexps:
		m = re.search(ur"(%s)" % regexp, newv)
		if m and m.group(2) in wrong:
			#print u"retirada: %s"%m.group(2).encode("ascii","replace")
			wrong.remove(m.group(2))

	#treiem formes col·loquials detectades, si estracta d'una pàgina de discussió
	if "hola" in wrong and page.namespace() % 2 != 0:
	   wrong.remove("hola")

	#cerquem elements esborrats
	if page.namespace() == 0 and newv:
		for tpl in whitelist:
			element1  = re.search(ur"(%s)" % tpl, oldv)
			element2  = re.search(ur"(%s)" % tpl, newv)
			plant1=plant2=""
			if element1:
				plant1 = element1.group(1)
			if element2:
				plant2 = element2.group(1)

			if not plant2 and plant1:
				missing.append(plant1)

	return (wrong, missing)

def edit(bot, evt, cmd):
	#Edició
	flags = cmd.dict['flags']
	if evt.chan == "#pt.wikipedia": return
	if "B" in flags:
		return True
	if bot._debug[4]: print u"[%s] <%r> [[%r]] o:%s d:%s out:" % (time.strftime("%H:%M:%S"), cmd.dict['user'], cmd.dict['page'], cmd.dict['oldid'], cmd.dict['diff']),

	site = get_site(evt.target)
	user = User(site, cmd.dict['user'])
	page = Page(site, cmd.dict['page'])
	summary = cmd.dict['summary']
	diffsize = cmd.dict['diffsize']
	diff = cmd.dict['diff']
	oldid = cmd.dict['oldid']
	log = bot.logs.IPs if user.is_anon() else bot.logs.users
	register_user(user, log, flags)
	title = wikiquote(page.title())
	output=""

	igns = bot.logs.igns['p'].copy()
	for p in igns:
		if bot.logs.igns['p'][p] < time.time():
			msg = u"Es torna a admetre les edicions a la pàgina %s%s%s" % (F.page(p))
			bot.vnd_msg(evt, msg)
			del bot.logs.igns['p'][p]
	igns = bot.logs.igns['u'].copy()
	for u in igns:
		if bot.logs.igns['u'][u] < time.time():
			msg = u"Es torna a admetre les edicions de l'usuari  %s%s%s" % (F.loggeduser(u))
			bot.vnd_msg(evt, msg)
			del bot.logs.igns['u'][u]
	if bot.logs.igns['p'].has_key(page.title()):
		if bot.logs.igns['p'][page.title()] > time.time():
			return
	if bot.logs.igns['u'].has_key(user.nick()):
		if bot.logs.igns['u'][user.nick()] > time.time():
			return

	editcount = get_numeds(user.nick(), log)
	diffL = "https://ca.wikipedia.org/?diffonly=1&diff=%s" % (diff,)

	if page.title() in (u"Usuari Discussió:IradiBot", u"Usuari Discussió:BotReversor", u"Usuari Discussió:BotPatrulla"):
		#afegir find_psq! per a que m'avise 5-10-09
		avis=u"S'ha deixat un missatge a la discussió d'%s https://%s/?diffonly=1&diff=%s" % (site.sitename(), title.strip(), diff)
		bot.alert("Coet", avis)
		if bot._debug[4]: print "E#2"
		return

	#examinem si s'ha introduït {{destrucció}}
	avis = ""
	if user.nick() != "BotPatrulla" and user.nick() not in site.sysops():
		try:
			revact, revant = page.revisions(oldid, diff)
		except NoSuchPage:
			bot.ctrl_msg(evt,
				u"&B;&r;list index out of range:&N; &B;sitename:&N; {sn}, &B;page&N; [[&l;{pg}&N;]] &t;{oi}&N; &o;{df}&N; "
				"https://{sn}/w/api.php?format=jsonfm&action=query&indexpageids&prop=revisions&revids={rv}&rvprop=content"
				"|user|timestamp" . format (
					sn = site.sitename(),
					pg = page.title(),
					oi = oldid,
					df = diff,
					rv = "|".join([oldid, diff])
				)
			)
			return True

		if revact and u"{{destrucció" in revact and u"{{destrucció" not in revant:
			diffL += " &r;&B;https://%s/wiki/%s?action=delete&N;" % (site.sitename(), title)
			avis = F.line(
				F.topic(u"Edició"),
				F.action(u"destrucció sol·licitada"),
				F.user(user.nick()),
				F.page(page.title()),
				F.summ(summary),
				F.link(diffL)
			)
			check=True

	#IradiBot avisa d'un vàndal insistent
	if user.nick() in ("BotReversor", "BotPatrulla", "IradiBot") and u"avís automàtic de robot per " in summary.lower() \
	and page._title.lower() == u"viquipèdia:observatori del vandalisme/avisos automàtics":
		vandal = summary.split("[[Special:Contributions/")[1].split("|")[0]
		section = re.search("/\* (.*?) \*/", summary)
		section = "#"+wikiquote(section.group(1)).replace("%",".") if section else ""
		avis = F.line(
			F.topic(u"Avís de bot"),
			F.user(user.nick()),
			F.page(page.title()),
			"El bot informa que l'usuari",
			F.vandal(vandal),
			u"ha vandalitzat, tres o més pàgines.",
			F.link("https://%s/wiki/Special:Contributions/%s" % (site.sitename(), wikiquote(vandal))),
			F.obs("https://%s/wiki/Viquip%%C3%%A8dia:Observatori_del_vandalisme/Avisos_autom%%C3%%A0tics?action=edit%s" % (site.sitename(), section))
		)

	if len(avis) > 0:
		bot.vnd_msg(evt, avis)
		#bot.call_admin()
		if bot._debug[4]: print "E#3"
		return

	#Si edita alguna cosa en el seu espai d'usuari, passem
	if page.canonical_ns() == "user" and user.nick() == page.base_title():
		if bot._debug[4]: print "E#4"
		return

	#reversions de bots i usuaris mitjançant el MW
	if re.search(r"des les edicions de: |Desfets els canvis |Bot: Rv\. edic\. ", summary) :
		vnd = re.search("\[\[(?:Es|S)pecial:Contribu[ct]ions/.*?\|(.*?)\]\]", summary).group(1)
		user_str = quiet_nick(user.nick(), bot.bots(("master", 0)).channels["##bots-ca"].users())
		msg = u"%(usr)s ha revertit l'edició de %(vnd)s a %(pg)s https://%(sn)s/?diffonly=1&diff=%(df)s &r;https://%(sn)s/wiki/Special:Contributions/%(qvnd)s&N;" % {
			"usr": F.user(user_str), "vnd": F.vandal(vnd), "qvnd": wikiquote(vnd),
			"pg": F.page(page.title()), "sn": site.sitename(), "oi": oldid, "df": diff,
		}
		bot.vnd_msg(evt, msg)
		if bot._debug[4]: print "E#5"
		return
	#reversió mitjançant l'opció 'desfés'
	elif summary.startswith(u"Es desfà la revisió "):
		vnd = re.search("\[\[(?:Es|S)pecial:Contribu[tc]ions/.*?\|(.*?)\]\]", summary).group(1)
		rvr_msg = u"{usr} ha desfeta l'edició de {vnd} a {page} https://{sname}/?diffonly=1&diff={diff} &r;https://{sname}/wiki/Special:Contributions/{qvnd}&N;".format(
			usr = F.user(user.nick()), vnd = F.vandal(vnd), page = F.page(page.title()),
			sname = site.sitename(), oldid = oldid, diff = diff,
			qvnd = wikiquote(vnd)
		)
		bot.vnd_msg(evt, rvr_msg)
		if bot._debug[4]: print "E#6"
		return

	#reversions d'usuaris mitjançant els popups
	elif re.search(ur"Reversió a l'edició del [\d\- :]+ per [^,]+, número \d+ usant [[:w:ca:Viquipèdia:Finestres emergents de navegació|popups]]", summary):
		rvid = int(re.search(ur"número (\d+) usant", summary).group(1), re.U)
		user_str = quiet_nick(user.nick(), bot.bots(("master", 0)).channels["##bots-ca"].users())
		vnd = page.reverts(endid = rvid)
		if len(vnd)==1:
			vnd = vnd[0]
			msg = u"{usr} ha revertit l'usuari {vnd} a la pàgina {page} amb els popups. https://{sn}?diffonly=1&diff={diff} &r;https://{sname}/wiki/Special:Contributions/{qvnd}&N;" % (
				F.user(user_str), F.page(page.title()),
				vnd,
				site.sitename(), oldid, diff,
				site.sitename(), wikiquote(vnd)
			)
		else:
			vnd = join_list(vnd, evt.lang)
			msg = u"{usr} ha revertit els usuaris {vnds} a la pàgina {page} amb els popups. https://{sname}/?diffonly=1&diff={diff}" .format (
				usr = F.user(user_str), vdns = vnd,
				page = F.page(page.title()),
				sname = site.sitename(), oldid = oldid, diff = diff,
			)
		bot.vnd_msg(evt, msg)
		if bot._debug[4]: print "E#7"
		return

	#si l'usuari no és IP i té més de 200 edicions, o és administrador obviem
	if (not user.is_anon() and editcount >= 200) or user.nick() in site.sysops() or user.nick() in site.halfbots():
		if bot._debug[4]: print "skipped: edits:%i sysop:%s bot:%s" % (editcount, user.nick() in site.sysops(), user.nick() in site.halfbots())
		if bot._debug[4]: print "E#8"
		return

	#eixides sobre vandalismes
	v_output = ""
	output = ""

	# Edició en una pàgina d'altre usuari
	if page.namespace() == 2 and user.is_anon():
			v_output = F.line(
				F.topic(u"Edició"),
				F.action(u"Edició en una pàgina d'usuari aliena"),
				F.user(user.nick()),
				F.page(page.title()),
				F.dsize(diffsize),
				F.summ(summary),
				F.link(diffL)
			)
	#Edició en el NS de Viquipèdia
	elif page.namespace() == 4:
		if "plantejament de preguntes" in page._title.lower():

			output=F.line(
				F.topic(u'Edició'),
				F.sugg("Dubte"),
				F.user(user.nick()),
				F.page(page.title()),
				F.dsize(diffsize),
				F.summ(summary),
				F.link(diffL)
				)
		if not (re.search(u'avaluació|decisions|demanats|etiquetes|introducció|petició|plantejament|propostes|proves|qualitat|viquipedistes|taverna|visites', page.title(), re.I)):
			# or (user.is_anon() and  in lwr_page):  #'votacions' in page.lower() or 'consulta' in page.lower() or
			v_output=F.line(
				F.topic(u'Edició'),
				F.action(u'Possible vandalisme en ns Viquipèdia'),
				F.user(user.nick()),
				F.page(page.title()),
				F.dsize(diffsize),
				F.summ(summary),
				F.link(diffL)
			)
	# Eliminació de contingut
	elif int(diffsize) < -1000 or (summary and re.search(ur"^Eliminat tot el contingut de la pàgina$|^Contingut canviat per .*?", summary)):
		prf_usr = user_flag(user, editcount)
		v_output = F.line(
			F.topic(u"Edició"),
			F.action("Possible blanqueig"),
			F.userflag(prf_usr),
			F.user(user.nick()),
			F.page(page.title()),
			F.dsize(diffsize),
			F.summ(summary),
			F.link(diffL)
		)
	#afegitó important
	elif int(diffsize) > 2000:
		txt = page.content()
		if not re.search(r"\[\[.*\]\]|\{\{.*\}\}|\[https://.*\]|==.*==|''.*''", txt):
			prf_usr=user_flag(user,editcount)
			v_output=F.line(
				F.topic(u"Edició"),
				F.action("Possible copyvio"),
				F.userflag(prf_usr),
				F.user(user.nick()),
				F.page(page.title()),
				F.dsize(diffsize),
				F.summ(summary),
				F.link(diffL))
	#Cercador de text inapropiat
	else:
		check = check_changes(page, oldid, diff)
		if [len(check[0]), len(check[1])] != [0, 0]:
			result = ""
			if len(check[0]) != 0:
				result += u"S'ha inserit una cadena sospitosa: %s." % (', '.join(check[0]))
			if len(check[1]) != 0:
				result += u"S'ha retirat una cadena important: %s." % (', '.join(check[1]))
			if result:
				v_output=F.line(
					F.topic(u"Edició"),
					F.action(u"REVERSIÓ"),
					F.match(result),
					F.user(user.nick()),
					F.page(page.title()),
					F.dsize(diffsize),
					F.summ(summary),
					F.link(diffL)
				)
	if len(v_output) > 0:
		bot.vnd_msg(evt, v_output)
		#bot.call_user(page)
		if bot._debug[4]: print "E#9",
	if len(output) > 0:
		bot.vnd_msg(evt, output)
		#bot.call_scholar()
		if bot._debug[4]: print "E#10",
	if bot._debug[4]: print "E#11"
edit.rule = RE_IRC_RC['edit']
edit.fullmsg = True
#edit.thread = True
edit.evttypes = ("pubmsg",)
edit.onchan = _main['chan']

def new(bot, evt, cmd):
	#Nova pàgina
	flags = cmd.dict['flags']
	if "B" in flags:
		return True
	if bot._debug[4]: print u"[%s] <%r> [[%r]] o:%s out:" % (time.strftime("%H:%M:%S"), cmd.dict['user'], cmd.dict['page'], cmd.dict['oldid']),

	site = get_site(evt.target)
	user = User(site, cmd.dict['user'])
	page = Page(site, cmd.dict['page'])
	summary = slice_summ(cmd.dict['summary'])
	oldid = cmd.dict['oldid']
	diffsize = cmd.dict['diffsize']
	log = bot.logs.IPs if user.is_anon() else bot.logs.users
	register_user(user, log, flags)
	editcount = get_numeds(user.nick(), log)
	title = wikiquote(page.title())
	diffL = "https://%s/wiki/%s" % (site.sitename(), title)
	txt=""; output = ""; v_output = ""

	igns = bot.logs.igns['p'].copy()
	for p in igns:
		if bot.logs.igns['p'][p] < time.time():
			msg = u"Es torna a admetre les edicions a la pàgina %s" % F.user(p)
			bot.vnd_msg(evt, msg.encode('utf-8'))
			del bot.logs.igns['p'][p]
	igns = bot.logs.igns['u'].copy()
	for u in igns:
		if bot.logs.igns['u'][u]<time.time():
			msg = u"Es torna a admetre les edicions de l'usuari  %s" % F.user(u)
			bot.vnd_msg(evt, msg.encode('utf-8'))
			del bot.logs.igns['u'][u]
	if bot.logs.igns['p'].has_key(page.title()):
		if bot.logs.igns['p'][page.title()] > time.time():
			return
	if bot.logs.igns['u'].has_key(user.nick()):
		if bot.logs.igns['u'][user.nick()] > time.time():
			return

	#Si edita al seu espai d'usuari, passem
	if page.namespace() in (2, 3) and page.base_title() == user.nick():
		if bot._debug[4]: print "N#2"
		return

	#si l'usuari no és IP i té més de 200 edicions, obviem els seus canvis
	if (not user.is_anon() and editcount >= 200) or user.nick() in site.sysops():
		if bot._debug[4]: print "N#3"
		return

	# EIXIDA VANDALISMES
	v_output = ""
	#Redirecció circular
	if int(diffsize) == len("#redirect ") + len(page.title()) \
	or re.search(ur"re(?:dir(?:ec(?:t|ciona)|igeix)|m(?:et|ite?ix)) (?:cap a)?", summary, re.I):
		if not txt: txt = page.content()
		re_Redirect = re.compile(ur"#redirect \[\[(.*?)\]\]",re.I)
		if re_Redirect.search(txt):
			redir = re_Redirect.search(txt).group(1)
			if redir == page.title():
				output=F.line(
					F.topic("Nou").
					F.topic(u"Redirecció circular"),
					F.user(user.nick()),
					F.page(page.title()),
					F.dsize(diffsize),
					F.summ(summary),
					F.link(diffL)
				)
	#Creació enana
	if int(diffsize) < 100:
		v_output = F.line(
			F.topic("Nou"),
			F.action(u"Creació ínfima"),
			F.user(user.nick()),
			F.page(page.title()),
			F.dsize(diffsize),
			F.summ(summary),
			F.link(diffL)
		)
		if not txt:
			txt = page.content()
		if page.namespace() == 1 and re.search(u"\{\{ ?(?:traduït[_ ]de|avaluació|copiat de)[^}]+?\}\}", txt, re.I):
			if bot._debug[4]: print "N#4"
			return
		if page.namespace() == 0 and not re.search(u"#redirect|\{\{ ?Petició de traducció[^}]+?\}\}", txt, re.I):
			pass
		elif page.namespace() == 1 and not re.search(u"\{\{ ?traduït de ?\|", txt, re.I):
			pass
		elif page.namespace() == 3 and not re.search(u"\{\{ ?benvinguda ?\}\}", txt, re.I):
			pass
		elif page.namespace() != 0:
			v_output=F.line(
				F.topic("Nou"),
				F.action(u"Creació en un ns estrany"),
				F.user(user.nick()),
				F.page(page.title()),
				F.dsize(diffsize),
				F.summ(summary),
				F.link(diffL)
			)
		else:
			if bot._debug[4]: print "N#4.1"
			v_output=""

	#Creació gran
	elif (page.namespace() == 0, int(diffsize) > 1500) == (True, True):
		#--- si l'usuari afegeix algun element de sintaxi wiki, ens fiem que no introdueix un copyvio
		if not txt: txt = page.content()
		if txt and not re.search(r"\[\[.*\]\]|\{\{.*\}\}|\[https://.*\]|==.*==|''.*''", txt):
			prf_usr = user_flag(user, editcount)
			v_output=F.line(
				F.topic("Nou"),
				F.action("Possible copyvio"),
				F.userflag(prf_usr),
				F.user(user.nick()),
				F.page(page.title()),
				F.dsize(diffsize),
				F.summ(summary),
				F.link(diffL)
			)
	#Cercador de text inapropiat
	else:
		check = check_changes(page, oldid, None)
		if [len(check[0]), len(check[1])] != [0, 0]:
			result = ""
			if len(check[0]) != 0:
				 result += u"S'ha inserit una cadena sospitosa: %s" % (', '.join(check[0]))
			if len(check[1]) != 0:
				result += u"S'ha retirat una cadena important: %s" % (', '.join(check[1]))
			if result:
				v_output = F.line(
					F.topic("Nou"),
					F.action("ESBORRAR"),
					F.match(checked),
					F.user(user.nick()),
					F.page(page.title()),
					F.dsize(diffsize),
					F.summ(summary),
					F.link(diffL)
				)
	if v_output:
		bot.vnd_msg(evt, v_output)
		#bot.call_sysop()
		if bot._debug[4]: print "N#5",
	if output:
		bot.vnd_msg(evt, output)
		#bot.call_user()
		if bot._debug[4]: print "N#6",
	if bot._debug[4]: print "N#7"
new.rule= RE_IRC_RC['new']
#new.thread = True
new.fullmsg = True
new.evttypes = ("pubmsg",)
new.onchan = _main['chan']

def newuser(bot, evt, cmd):
	#Nou usuari
	site = get_site(evt.target)
	user = User(site, cmd.dict['user'])
	page = Page(site, cmd.dict['page'])
	flags = cmd.dict['flags']
	url = " https://%s/wiki/Special:Log/newusers?user=%s"%(site.sitename(), wikiquote(user.nick()))

	#enviem en cas que es cree un compte que continga "WOW" o que un usuari cree un altre compte
	#en eixe cas podríem estar parlant de comptes titella (create2 = maybe a puppet count)
	if re.search(".*(?:wow|(?:willy )?on wheels).*", user.nick(), re.I):
		v_output = F.line(
			F.topic("Nou usuari"),
			F.action(u"Nom sospitós"),
			F.user(user.nick()),
			F.link(url)
		)
		bot.vnd_msg(evt, v_output)
	elif flags == 'create2':
		output = F.line(
			F.topic("Nou usuari"),
			F.user(user.nick()),
			"crea un nou compte per a",
			F.red(cmd.dict['element1']),
			F.link(url)
		)
		bot.vnd_msg(evt, output)
newuser.rule = RE_IRC_RC['create']
newuser.aliases = [RE_IRC_RC['create2']]
newuser.fullmsg = True
newuser.evttypes = ("pubmsg",)
newuser.onchan = _main['chan']

def move(bot, evt, cmd):
	#Trasllat
	site = get_site(evt.target)
	user = User(site, cmd.dict['user'])
	page = Page(site, cmd.dict['page'])
	flags = cmd.dict['flags']
	summary = cmd.dict['summary']
	log = bot.logs.IPs if user.is_anon() else bot.logs.users
	register_user(user, log, flags)
	if user.nick() in site.sysops():
	   return

	old_title = Page(site, cmd.dict['element1'])
	new_title = Page(site, cmd.dict['element2'])
	#new_title  = re.sub(u"\x0[23]\d{0,2}","",new_title) #hi ha caràcters que són propi dels colors de l'IRC
	diffL = u'https://%s/wiki/%s' % (site.sitename(), wikiquote(new_title.title()))
	output =F.line(
		F.topic("Trasllat"),
		F.user(user.nick()),
		F.mov_f(old_title.title()),
		u" → ",
		F.mov_t(new_title.title()),
		F.summ(summary),
		F.link(diffL)
	)

	#EIXIDA VANDALISME
	v_output = u""
	#si es reanomena una pàgina d'un article a un altre espai
	if old_title.namespace() != new_title.namespace():
		v_output=F.line(
			F.topic("Trasllat"),
			F.action("Trasllat entre diferents noms d'espai"),
			F.user(user.nick()),
			F.mov_f(old_title.title()),
			u" → ",
			F.mov_t(new_title.title()),
			F.summ(summary),
			F.link(diffL)
		)
		bot.vnd_msg(evt, v_output)
		#bot.call_user(page)
	#si es canvia el nom d'un usuari reanomenant la pàgina.
	elif old_title.canonical_ns() == "user" and new_title.canonical_ns() == "user":
		#si trasllada al seu espai, passem
		old_user = old_title.base_title()
		new_user = new_title.base_title()
		if old_user == new_user == user:
			return
		v_output = F.line(
			F.topic("Trasllat"),
			F.action("Reanomenament d'usuari erroni"),
			F.user(user.nick()),
			F.mov_f(old_title),
			u" → ",
			F.mov_t(new_title),
			F.summ(summary),
			F.link(diffL)
		)
		bot.vnd_msg(evt, v_output)
		##bot.call_user()
move.rule = RE_IRC_RC['move']
#move.thread = True
move.fullmsg = True
move.evttypes = ("pubmsg",)
move.onchan = _main['chan']

def upload(bot, evt, cmd):
	#Càrrega d'imatge
	site = get_site(evt.target)
	user = User(site, cmd.dict['user'])
	image = wikiquote(cmd.dict['element1'])
	page = Page(site, cmd.dict['element1'])
	diffL = "https://ca.wikipedia.org/wiki/%s" % image
	flag = "Pujada" if cmd.dict['flags']=="upload" else u"Actualització"
	flag += " d'imatge"
	#output=F.line(F.special(flag), F.user(user.nick()), "puja", F.page(image), F.link(diffL))

	#EIXIDA VANDALISME
	v_output = u""
	txt = page.content()
	if [u'{{' in ex, u'}}' in ex] != [True, True]:
		lic=F.action(u'sense etiquetes de llicència')
	else:
		lic=F.sugg(u'reviseu la llicència')
	v_output+=F.line(
		F.special(flag),
		lic,
		F.user(user.nick()),
		F.summ(cmd.dict['summary']),
		F.link(diffL)
	)
upload.rule = RE_IRC_RC['upload']
upload.fullmsg = True
upload.evttypes = ("pubmsg",)
upload.onchan = _main['chan']
upload.load=False

def delete(bot, evt, cmd):
	site = get_site(evt.target)
	mBot = bot.bots(("master", 0))
	admin  = "&U;&+g;&B;%s&N;" % (quiet_nick(cmd.dict['user'], mBot.channels[mBot.testchan].users()))
	page = Page(site, cmd.dict['element1'])
	title = wikiquote(cmd.dict['element1'])

	#Esborrament
	if cmd.dict['flags'] == "delete":
		del_url = "https://%s/wiki/Special:Undelete/%s" % (site.sitename(), title)
		output = F.line(
			F.special("Esborrament"),
			F.sysop(admin),
			"esborra",
			F.page(page.title()),
			F.summ(cmd.dict['summary']),
			F.link(del_url)
		)
		bot.vnd_msg(evt, output)

	#Restaurament
	elif cmd.dict['flags'] == "restore":
		output = F.line(
			F.special("Restaurament"),
			F.sysop(admin),
			"restaura",
			F.page(page.title()),
			F.summ(cmd.dict['summary']),
			F.link("https://%s/wiki/%s" % (site.sitename(), title))
		)
		bot.vnd_msg(evt, output)
delete.rule = RE_IRC_RC['delete']
delete.fullmsg = True
delete.evttypes = ("pubmsg",)
delete.onchan = _main['chan']

def block(bot, evt, cmd):
	#Bloqueig d'usuari
	site = get_site(evt.target)
	blocked = cmd.dict['blocked']
	mBot = bot.bots(("master", 0))
	admin = "&U;&+g;&B;%s&N;" % (quiet_nick(cmd.dict['user'], mBot.channels[mBot.testchan].users()))
	output = ""

	if cmd.dict['flags'] == "block":
		output+=F.line(
			F.special("Bloqueig"),
			F.sysop(admin),
			"bloca l'usuari",
			F.vandal(blocked),
			"per un temps:",
			F.number(cmd.dict['while']),
			F.summ(cmd.dict['summary']),
			F.link("https://ca.wikipedia.org/wiki/Special:Contributions/%s" % wikiquote(blocked))
		)
		if is_ip(blocked):
			try:
				bot.logs.IPs[blocked][4]+=1
			except KeyError:
				#IP no registrada
				pass
			bot.vnd_msg(evt, output)

	#Desbloqueig d'usuari
	elif cmd.dict['flags'] == "unblock":
		output+=F.line(
			F.special("Desbloqueig"),
			F.sysop(admin),
			"treu bloqueig a",
			F.vandal(blocked),
			F.summ(cmd.dict['summary']),
			F.link("https://ca.wikipedia.org/wiki/Special:Contributions/%s" % wikiquote(blocked))
		)
		bot.vnd_msg(evt, output)
	time.sleep((2+len(output))/120.0)
block.rule = RE_IRC_RC['block']
block.aliases = [RE_IRC_RC['unblock']]
block.fullmsg = True
block.evttypes = ("pubmsg",)
block.onchan = _main['chan']

def protect(bot, evt, cmd):
	#Protecció d'usuari
	site = get_site(evt.target)
	page = Page(site, cmd.dict['element1'])
	flags = cmd.dict['flags'] #["protect","unprotect","modify"]
	mBot = bot.bots(("master", 0))
	admin = "&U;&+g;&B;%s&N;" % (quiet_nick(cmd.dict['user'], mBot.channels[mBot.testchan].users()))
	output = ""
	if flags == "protect":
	   flag1 = u"Protecció"
	   flag2 = "protegeix"
	elif flags == "unprotect":
	   flag1 = u"Desprotecció"
	   flag2 = "desprotegeix"
	elif flags == "modify":
	   flag1 = u"Modificació"
	   flag2 = u"modifica la protecció"
	output += F.line(F.special(flag1),
				   F.sysop(admin),
				   flag2+u" la pàgina",
				   F.page(page.title()),
				   F.summ(cmd.dict['summary']),
				   F.link("https://ca.wikipedia.org/wiki/Especial:Registre/protect?page=%s" % wikiquote(page.title())))
	bot.vnd_msg(evt, output)
protect.rule = RE_IRC_RC['protect']
protect.aliases = [RE_IRC_RC['unprotect']]
protect.fullmsg = True
protect.evttypes = ("pubmsg",)
protect.onchan = _main['chan']

def patrol(bot, evt, cmd):
	return #load it, but don't make anythinbot.logs.
	site = get_site(evt.target)
	user = User(site, cmd.dict['user'])
	page = Page(site, cmd.dict['element1'])
	output = ""

	output =  F.line(
	F.special("Patrulla"),
		F.user(user.nick()),
		"ha marcat",
		F.page(page.title()),
		"com a supervisada.",
		F.link("https://ca.wikipedia.org/wiki/Special:Newpages")
	)
	bot.patrol_msg(evt, output)
patrol.rule = RE_IRC_RC['patrol']
patrol.fullmsg = True
patrol.evttypes = ("pubmsg",)
patrol.onchan = _main['chan']
patrol.load = False

def wmtest(bot, evt, cmd):
	if hasattr(bot, "features"):
		bot.re_send_to("##wikipedia-ca-proves", evt.msg)
wmtest.rule = re.compile(".*")
wmtest.fullmsg = True
wmtest.evttypes = ("pubmsg",)
wmtest.onchan = _main['chan']
wmtest.load=False

minimum_of_edits = 50
def edit2(bot, evt, cmd):
	#edició d'articles
	#Reversions admins, usuaris i bot
	site = get_site(evt.target)
	title = F.page(cmd.dict["page"])
	user = User(site, cmd.dict["user"])
	mBot = bot.bots(("master", 0))
	user_str = quiet_nick(user.nick(), mBot.channels[mBot.testchan].users())
	user_str = u"&+e;&U;%s&N;" % user_str #F.user(user.nick())
	flags = " (&r;%s&N;)" % cmd.dict["flags"] if cmd.dict["flags"] else ""
	diffsize = F.dsize(cmd.dict["diffsize"])
	diff = cmd.dict['diff']
	oldid = cmd.dict['oldid']
	summary = cmd.dict['summary']

	if re.search(ur"Revertides les edicions de: |Desfets els canvis |Bot: Rv\. edic\. |Es desfà la revisió ", summary) :
		vnd=re.search("\[\[(?:Es|S)pecial:Contributions/.*?\|(.*?)\]\]", summary)
		if vnd:
			axn = "desfet" if "es desf" in summary else "revertida"
			msg=u"%(usr)s ha %(axn)s l'edició de %(vnd)s a %(page)s https://%(sname)s/?diffonly=1&diff=%(diff)s &r;https://%(sname)s/wiki/Special:Contributions/%(qvnd)s &N;" % {
				"usr": user_str, "axn": axn, "vnd": u"&r;%s&N;" % vnd.group(1), "page": title,
				"sname": site.sitename(), "diff": diff, "oldid": oldid,
				"qvnd": wikiquote(vnd.group(1))
			}
		else: return True
		bot.patrol_msg(evt, msg)
		return True
	#reversions popups
	elif re.search(ur"Reversió a l'edició del [\d\- :]+ per [^,]+, número \d+ usant [[:w:ca:Viquipèdia:Finestres emergents de navegació|popups]]", summary):
		rvid = re.search(ur"número (\d+) usant", summary, re.U).group(1)
		vnd = page.reverts(rvid)
		if len(vnd)==1:
			vnd = vnd[0]
			msg = u"{usr} ha revertit l'usuari {vnd} a la pàgina {page} amb els popups. https://{sname}/?diffonly=1&diff={diff} &r;https://{sname}/wiki/Special:Contributions/{qvnd}&N;" .format (
				usr = F.user(user_str), page = F.page(page.title()),
				vnd = vnd,
				sname = site.sitename(), oldid = oldid, diff = diff,
				qvnd=wikiquote(vnd)
			)
		else:
			vnd = join_list(vnd, evt.lang)
			msg = u"{usr} ha revertit els usuaris {vnd} a la pàgina {pg} amb els popups. https://{sn}/?diffonly=1&diff={df}" .format (
				usr = F.user(user_str), pg = F.page(page.title()),
				vnd = vnd,
				sn = site.sitename(), oi = oldid, df = diff,
			)
		return True
	if cmd.dict["bot"] or not cmd.dict["patrol"]:
		return True
	msg= u"%s ha editat %s%s %s" % (user_str, title, flags, diffsize)
	if not is_ip(cmd.dict['user']):
		if user.info('editcount') > minimum_of_edits: return True
		msg += u" (té %i edicions)" % user.info('editcount')
	if summary: msg+= u" (%s)" % summary
	msg+=" https://ca.wikipedia.org/?diffonly=1&diff=%s" % diff
	bot.patrol_msg(evt, msg)
edit2.rule = RE_IRC_RC['edit']
edit2.fullmsg = True
#edit2.thread = True
edit2.evttypes = ("pubmsg",)
edit2.priority="low"
edit2.onchan = _main['chan']

def art_diff():
	for proj in projects:
		proj['arts'] = proj['site'].get_articles()
	for proj in loan_projects:
		proj['diff'] = proj['arts'] - _main['arts']

def new2(bot, evt, cmd):
	lang = None; site = None
	for proj in projects:
		if evt.target == proj['chan']:
			lang = proj['code']
			site = proj['site']
			break
	if not lang:
		lang = evt.target[1:].split(".")[0]
		if lang == "pt": return
		site = get_site(evt.target)

	user = User(site, cmd.dict["user"])
	page = Page(site, cmd.dict["page"])
	flags = u" (&r;%s&N;)" % cmd.dict["flags"] if cmd.dict["flags"] else ""
	diffsize = cmd.dict["diffsize"]
	summary = cmd.dict['summary']
	mBot = bot.bots(("master", 0))
	user_str = quiet_nick(user.nick(), mBot.channels[mBot.testchan].users())
	user_str = u"&+e;&U;%s&N;" % user_str
	title = u"[[&l;%s&N;]]" % cmd.dict["page"]
	msg=""

	if lang in [p['code'] for p in loan_projects] and page.namespace() != 0:
		return True
	if lang == _main['code']:
		msg=u"%s ha creat %s%s [%s]" % (user_str, title, flags, diffsize)
	else:
		proj = _prev if lang == _prev['code'] else _next
		msg = u"un &t;%s&N; anomenat %s ha creat %s%s [%s]" % (proj['gent'], user_str, title, flags, diffsize)
	if page.namespace() == 0:
		art_diff()
		if lang != "ca":
			if bot._debug[4]: print "{time} NEW {lang} | _p: arts({parts}) diff({pdiff}) | _n: arts({narts}) diff({ndiff})" . format(
				time = time.strftime("[%H:%M:%S]"),
				lang = lang,
				parts = _prev['arts'], pdiff = _prev['diff'],
				narts = _next['arts'], ndiff = _next['diff']
			)
		_prev['txt'] = (u" només queden ", " per igualar-los") if _prev['diff'] > 0 else ("els superem de ","")
		_next['txt'] = (u" només queden ", " per igualar-los") if _next['diff'] > 0 else ("els superem de ","")
		#_p: #vi.wikipedia arts(358971) diff(-8690) | _n: #uk.wikipedia arts(372990) diff(5329)
		if not hasattr(bot, "verbose"): bot.verbose=False
		if not bot.verbose:
			if lang == _prev['code'] and _prev['diff'] > -500: return
			if lang == _next['code'] and _next['diff'] > 500: return
		if -1 <= _next['diff'] <= 0:
			users = mBot.channels[bot.newartchan].users()
			msg=u"%s JA ELS HEM SUPERAT!!!" % ", ".join(users)
		got_goal = ""; number= ""
		if lang == _main['code']:
			number = u", és la pàgina número: &t;%s&N;" % format_number( _main['arts'], 0)
			if bot._debug[4]: print "rc.py 918", "site: %s abrSite: %s" % (_prev['site'], _prev['site'].abredged_sitename())
			number += u". %s &t;%s&N; (&r;%i&N;) | %s &t;%s&N; (&r;%i&N;)" % (
				_prev['site'].abredged_sitename(),
				format_number(_prev['arts'], 0), _prev['diff'],
				_next['site'].abredged_sitename(),
				format_number(_next['arts'], 0), _next['diff'],
			)
			goal = int(str(_main['arts'])[0]) + 1
			power = len(str(_main['arts'])[1:])
			goal = goal * (10 ** power)
			remains  = goal - _main['arts']
			if remains == 0:
				users = mBot.channels[bot.newartchan].users()
				got_goal = "%s JA TENIM L'ARTICLE %i!!!" % (", ".join(users), format_number(goal, 0))
			if remains < 500:
				number += u" | obj &y;%i&N;" % remains
		elif lang == _prev['code']: # and 0 >= _prev['diff'] >= -500:
			number=u", és la pàgina número: &t;%s&N;" % format_number(_prev['arts'], 0)
			number+=u". Nosaltres en tenim &t;%s&N;,%s&r;%i&N;%s" % (
				format_number(_prev['arts']),
				_prev['txt'][0], _prev['diff'],
				_prev['txt'][1]
			)
		elif lang == _next['code']: # and 0 <= _next['diff'] <= 500:
			number = u", és la pàgina número: &t;%s&N;" % format_number(_next['arts'], 0)
			number += u". Nosaltres en tenim &t;%s&N;,%s&r;%i&N;%s" % (
				format_number(_next['arts'], 0),
				_next['txt'][0], _next['diff'],
				_next['txt'][1]
			)
		if number:
			msg2 = u"%s%s" % (msg, number)
			bot.newpages_msg(evt, msg2)
		if got_goal:
			bot.newpages_msg(evt, got_goal)
		if lang != "ca":
			return True
	if cmd.dict["bot"] or not cmd.dict["patrol"]:
		return True
	if lang == "ca" and not user.is_anon():
		if user.info('editcount') > minimum_of_edits: return True
		msg += u" (té %i edicions)" % user.info('editcount')
	if lang == "ca" and summary:
		msg += u" (%s)" % summary
	msg+=" https://%s.wikipedia.org?oldid=%s" % (lang, cmd.dict['oldid'])
	if lang == "ca":
		bot.patrol_msg(evt, msg)
	return True
new2.rule= RE_IRC_RC['new']
#new2.thread = True
new2.fullmsg = True
new2.evttypes = ("pubmsg",)
new2.priority = "low"
